<?php

declare (strict_types=1);
namespace app\admin\controller;
use app\common\model\server\Setting;
use think\facade\Request;
/**
 * 
 * Class Update
 * @package app\admin\controller
 */
class Update extends BaseAdmin
{
	
	public function newVer(){
		
	} 

    public  function ver()
    {
        $data=Setting::find(1)->toArray();
        $url='http://upload.shareadd.cn/api/update/getverlist';
        $data['type']='service';
        $data['num']=0;
        $res=$this->curl_post($url,$data);
        $list=json_decode($res,true);
        if($list['code']==1){
            $type=!empty($data['secret_key']) ? 2 : 1;
            $code=str_replace('.','',$data['version']);
            foreach($list['data'] as $k=>$v){
                if($v['type']==$type && $code+1==$v['code']){
                    $data['num']=1;
                    break;
                }
            }
        }
        return $this->success($data);
    }
    public function getverlist(){
        $url='http://upload.shareadd.cn/api/update/getverlist';
        $data['type']='service';
        $res=$this->curl_post($url,$data);
        $list=json_decode($res,true);
        if($list['code']==1){
            return $this->success($list['data']);
        }
        return $this->error($list['msg']);
    }
    public  function checkver()
    {
        $request = Request::instance(); // 获取请求对象
        $name=$request->get('name');
        if($name){ //删除压缩包
            $del['name']=$name;
            $urls='http://upload.shareadd.cn/api/update/editzip';
            $this->curl_post($urls,$del);
            return $this->success('成功1');
        }
        $setting=Setting::find(1);
        $data['version']=$setting['version'];
        $data['secret_key']=$setting['secret_key'];
        $data['type']='service';
        $urls='http://upload.shareadd.cn/api/update/index';
        $res=$this->curl_post($urls,$data);
       
        $da=json_decode($res,true);
        
        if($da['code']==200){
            if($setting['version']==$da['banben']){
                $li['msg']='已是最新版本，无需更新';
                $li['version']=$da['banben'];
                return $this->success($li);
            }
            $url = $da['url']; // 压缩文件的URL
            $saveDir = './upload/'; // 保存下载文件的目录
            $unzipDir =app()->getRootPath(); // 解压目标目录
            // 确保目录存在
            if (!is_dir($saveDir)) {
                mkdir($saveDir, 0777, true);
            }
            if (!is_dir($unzipDir)) {
                mkdir($unzipDir, 0777, true);
            }else{
                chmod($unzipDir,0755);
            }
            
            $fileName = basename($url);
            $filePath = $saveDir . $fileName;
            //修改文件的权限
           
            // 下载文件
            $this->downloadFile($url, $filePath);
            chmod($filePath,0755);
           // echo "文件下载成功。\n";
           // 解压文件
            $this->unzipFile($filePath, $unzipDir);
            // echo "文件解压成功。\n";
            // 解压完成后删除压缩文件
            
            if (unlink($filePath)) {
                //echo "压缩文件已删除。\n";
                (new Setting)->update(['id'=>$setting['id'],'version'=>$da['banben']]);
            }
        }
        $data['version']=!empty($da['banben']) ? $da['banben'] : $setting['version'];
        $data['msg']=!empty($da['msg']) ? $da['msg'] : '成功2';
        $data['name']=!empty($da['name']) ? $da['name'] : '';
        return $this->success($data);
    }
    //解压文件
    public function unzipFile($zipFilePath, $targetDir) {
      
        // 创建ZipArchive对象
        $zip = new \ZipArchive;
        // 打开ZIP文件
        if ($zip->open($zipFilePath) === TRUE) {
            // 解压档案到指定目录
            if ($zip->extractTo($targetDir)) {
                //echo "文件已成功解压到 {$targetDir}";
                 $zip->close();
                return true;
            } else {
                $lastError = error_get_last();
                //echo "解压失败！原因可能是: " . $lastError['message'];
                tips("解压失败！原因可能是: " . $lastError['message']);
                return false;
            }
            // 关闭ZIP文件
            $zip->close();
        } else {
            //echo "无法打开ZIP文件: {$zipFilePath}";
            tips("无法打开ZIP文件: {$zipFilePath}");
            return false;
        }

    }
    //下载指定文件
    public function downloadFile($url, $savePath) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        $fileContent = curl_exec($ch);
        curl_close($ch);
    
        if (file_put_contents($savePath, $fileContent)) {
            return true;
        } else {
            return false;
        }
    }
    public function curl_post($url, $postData) {
        $ch = curl_init();
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        $response = curl_exec($ch);
        
        if (curl_errno($ch)) {
            // 错误处理
            echo 'Error:' . curl_error($ch);
        }
        
        curl_close($ch);
        
        return $response;
    }

}

